<template>
    <j-modal
      width="80%"
      :title="title"
      :visible.sync="editModalVisible"
      :fullscreen.sync="fullscreen"
      :switch-fullscreen="switchFullscreen"
      @cancel="handleCancleDbSync"
      :destroyOnClose="true"
    >
      <template slot="footer">
        <a-button @click="handleCancleDbSync">关闭</a-button>
        <a-button type="primary" :loading="syncLoading" @click="handleDbSync">确定</a-button>
      </template>
      <div class="table-page-search-wrapper warp">
        <a-form-model layout="horizontal" labelAlign="right" ref="ruleForm" :label-col="labelCol" :wrapper-col="wrapperCol" :model="formData" :rules="rules">
          <a-row :gutter="24">
            <a-col :xl="8" :lg="8" :md="8" :sm="24" >
              <a-form-model-item label="姓名" prop="username">
                <j-select-user-by-dep
                  :multi="false"
                  v-model="formData.username"
                >
                </j-select-user-by-dep>
              </a-form-model-item>
            </a-col>
            <a-col :xl="8" :lg="8" :md="8" :sm="24">
              <a-form-model-item label="部门">
                <j-select-depart v-model="formData.departId"></j-select-depart>
              </a-form-model-item>
            </a-col>
            <a-col :xl="8" :lg="8" :md="8" :sm="24">
              <a-form-model-item label="试用期发放比例" prop="probationScale">
                <a-input type="number" v-model="formData.probationScale" placeholder="请输入试用期发放比例"/>
              </a-form-model-item>
            </a-col>
            <a-col :xl="8" :lg="8" :md="8" :sm="24" >
              <a-form-model-item label="入职日期" prop="entryDate">
                <a-date-picker class="picker" @change="(date,dateString) => this.handleChanegPicker(dateString,'entryDate')" :value="formData.entryDate" placeholder="请选择入职日期"/>
              </a-form-model-item>
            </a-col>
            <a-col :xl="8" :lg="8" :md="8" :sm="24" >
              <a-form-model-item label="转正日期" prop="confirmationDate">
                <a-date-picker class="picker" @change="(date,dateString) => this.handleChanegPicker(dateString,'confirmationDate')" :value="formData.confirmationDate" placeholder="请选择转正日期"/>
              </a-form-model-item>
            </a-col>
            <a-col :xl="8" :lg="8" :md="8" :sm="24" >
              <a-form-model-item label="离退日期">
                <a-date-picker class="picker" @change="(date,dateString) => this.handleChanegPicker(dateString,'departureDate')" :value="formData.departureDate" placeholder="请输入离退日期"/>
              </a-form-model-item>
            </a-col>
            <a-col :xl="8" :lg="8" :md="8" :sm="24">
              <a-form-model-item label="停薪日期">
                <a-date-picker class="picker" @change="(date,dateString) => this.handleChanegPicker(dateString,'nopayDate')" :value="formData.nopayDate" placeholder="请输入停薪日期"/>
              </a-form-model-item>
            </a-col>
            <a-col :xl="8" :lg="8" :md="8" :sm="24">
              <a-form-model-item label="工资卡号" prop="wageCard">
                <a-input v-model="formData.wageCard" placeholder="请输入工资卡号" />
              </a-form-model-item>
            </a-col>
            <a-col :xl="8" :lg="8" :md="8" :sm="24">
              <a-form-model-item label="薪资方案" prop="salaryTemplateCode">
                <j-popup
                :value="formData.salaryTemplateCode"
                :trigger-change="true"
                org-fields="template_code,id"
                dest-fields="salaryTemplateCode,id"
                field="salaryTemplateCode"
                code="hr_salary_template_v"
                @callback="popupCallbackTemplate"/>
              </a-form-model-item>
            </a-col>
            <a-col :xl="8" :lg="8" :md="8" :sm="24">
              <a-form-model-item label="社保方案" prop="insuranceTemplateCode">
                <j-popup
                :value="formData.insuranceTemplateCode"
                :trigger-change="true"
                org-fields="template_code,id"
                dest-fields="insuranceTemplateCode,id"
                field="insuranceTemplateCode"
                code="hr_insurance_template_v"
                @callback="popupCallbackInsurance"/>
              </a-form-model-item>
            </a-col>
            <a-col :xl="8" :lg="8" :md="8" :sm="24">
              <a-form-model-item label="执行日期" prop="executeDate">
                <a-date-picker class="picker" @change="(date,dateString) => this.handleChanegPicker(dateString,'executeDate')" :value="formData.executeDate" placeholder="请输入执行日期"/>
              </a-form-model-item>
            </a-col>
          </a-row>
        </a-form-model>
        <a-tabs :tabBarStyle="{marginBottom: '0px'}">
          <a-tab-pane key="1" tab="薪资信息" force-render>
            <salary-item-table ref="vxeTable1" :dataSource="personnelSalaryItems"/>
          </a-tab-pane>
          <a-tab-pane key="2" tab="社保公积金" force-render>
            <social-insurance-table ref="vxeTable2" :dataSource="personnelInsuranceItems"/>
          </a-tab-pane>
        </a-tabs>
      </div>
    </j-modal>
</template>
<script>
import { postAction, putAction, getAction } from '@/api/manage'
import JSelectUserByDep from '@/components/jeecgbiz/JSelectUserByDep'
import JSelectDepart from '@/components/jeecgbiz/JSelectDepart'
import SalaryItemTable from '../modules/SalaryItemTable'
import SocialInsuranceTable from '../modules/SocialInsuranceTable'
export default {
  name: 'SalaryUserModal',
  components: {
    JSelectUserByDep,
    JSelectDepart,
    SocialInsuranceTable,
    SalaryItemTable
  },
  data() {
    return {
      tableColumn: [
        { type: 'seq', width: 60 },
        { field: 'salaryItem.itemName', title: '薪资项目' },
        { field: 'accountCycle', title: '核算方式', slots: { default: ({ row }) => {
          if (row.salaryItem) {
            return ''
          } else {
            return ''
          }
        } }},
        { field: 'salaryTemplateDetail.lowerLimit', title: '金额下限' },
        { field: 'salaryTemplateDetail.upperLimit', title: '金额上限' },
        { field: 'amount', title: '执行金额/标准', editRender: { name: '$input', props: { type: 'number' }}},
        { field: 'salaryItem.remarks', title: '备注' }
      ],
      validRules: {
        amount: [
          { required: true, message: '请填写执行金额/标准' },
          { validator: this.amount }
        ]
      },
      editModalVisible: false,
      title: '编辑',
      syncLoading: false,
      fullscreen: true,
      switchFullscreen: true,
      labelCol: { span: 6 },
      wrapperCol: { span: 18 },
      url: {
        edit: '/hr/salary/personnel/editWithChildren',
        add: '/hr/salary/personnel/addWithChildren',
        template: '/hr/salary/template/listSalaryTemplateDetailByTemplateCode',
        insurance: '/hr/insurance/template/listInsuranceTemplateDetailByTemplateCode',
        personnelSalaryItem: '/hr/salary/personnel/listPersonnelSalaryItemByUsername',
        personnelInsuranceItem: '/hr/salary/personnel/listPersonnelInsuranceItemByUsername'
      },
      rules: {
        username: [
          { required: true, message: '请选择人员', trigger: 'change' }
        ],
        probationScale: [
          { required: true, message: '请输入试用期发放比例', trigger: 'change' }
        ],
        entryDate: [
          { required: true, message: '请选择入职日期', trigger: 'change' }
        ],
        confirmationDate: [
          { required: true, message: '请选择转正日期', trigger: 'change' }
        ],
        wageCard: [
          { required: true, message: '请输入工资卡号', trigger: 'change' }
        ],
        salaryTemplateCode: [
          { required: true, message: '请选择薪资方案', trigger: 'change' }
        ],
        insuranceTemplateCode: [
          { required: true, message: '请选择社保方案', trigger: 'change' }
        ],
        executeDate: [
          { required: true, message: '请选择执行日期', trigger: 'change' }
        ]
      },
      formData: {},
      disableSubmit: false,
      personnelSalaryItems: [],
      personnelInsuranceItems: []
    }
  },
  methods: {
    handleCancleDbSync() { // 关闭
      this.editModalVisible = false
    },
    edit(record) {
      this.formData = JSON.parse(JSON.stringify(record))
      this.editModalVisible = true
      this.getPersonnelSalaryItem(record.username)
      this.getPersonnelInsuranceItem(record.username)
    },
    add() {
      this.formData = {}
      this.editModalVisible = true
    },
    getPersonnelSalaryItem(username) {
      getAction(this.url.personnelSalaryItem, { username: username }).then(res => {
        if (res.success) {
          this.personnelSalaryItems = res.result.records
        } else {
          this.$message.warning(res.message)
        }
      })
    },
    getPersonnelInsuranceItem(username) {
      getAction(this.url.personnelInsuranceItem, { username: username }).then(res => {
        if (res.success) {
          this.personnelInsuranceItems = res.result.records
        } else {
          this.$message.warning(res.message)
        }
      })
    },
    handleDbSync() { // 弹窗点击确定
      Promise.all([
        this.$refs.vxeTable1.validate(),
        this.$refs.vxeTable2.validate(),
        this.$refs['ruleForm'].validate()
      ]).then((res) => {
        this.updateData()
      }).catch(function(reason) {
        console.log(reason)
      })
    },
    updateData(params) { // 保存提交数据
      this.syncLoading = true
      const data1 = this.$refs.vxeTable1.getTableData()
      this.formData.personnelSalaryItems = data1.fullData
      const data2 = this.$refs.vxeTable2.getTableData()
      this.formData.personnelInsuranceItems = data2.fullData
      if (this.formData.id) {
        putAction(this.url.edit, this.formData).then((res) => {
          if (res.success) {
            this.$message.success(res.message)
            this.editModalVisible = false
            this.$emit('ok')
          } else {
            this.$message.warning(res.message)
          }
          this.syncLoading = false
        }).finally(() => {
          // this.loading = false
        })
      } else {
        postAction(this.url.add, this.formData).then((res) => {
          if (res.success) {
            this.$message.success(res.message)
            this.editModalVisible = false
            this.$emit('ok')
          } else {
            this.$message.warning(res.message)
          }
          this.syncLoading = false
        }).finally(() => {
          // this.loading = false
        })
      }
    },
    handleChanegPicker(dateString, key) {
      this.formData[key] = dateString
    },
    popupCallbackTemplate(row) {
      this.formData.salaryTemplateCode = row.salaryTemplateCode
      this.getTemplate(row.salaryTemplateCode)
    },
    popupCallbackInsurance(row) {
      this.formData.insuranceTemplateCode = row.insuranceTemplateCode
      this.getInsurance(row.insuranceTemplateCode)
    },
    getTemplate(templateCode) {
      getAction(this.url.template, { templateCode: templateCode }).then(res => {
        if (res.success) {
          this.personnelSalaryItems = []
          const list = res.result.records || []
          list.forEach(item => {
            this.personnelSalaryItems.push({
              salaryTemplateDetailId: item.id,
              salaryItem: item.salaryItem,
              salaryTemplateDetail: item
            })
          })
        } else {
          this.personnelSalaryItems = []
        }
      })
    },
    getInsurance(templateCode) {
      getAction(this.url.insurance, { templateCode: templateCode }).then(res => {
        if (res.success) {
          this.personnelInsuranceItems = []
          const list = res.result.records || []
          list.forEach(item => {
            this.personnelInsuranceItems.push({
              insuranceTemplateDetailId: item.id,
              insuranceTemplateDetail: item
            })
          })
        } else {
          this.personnelInsuranceItems = []
        }
      })
    },
    handleChangeUser(data) {
      console.log(data)
    }
  }
}
</script>
<style lang="less">
.picker{
  width:100%;
}
</style>
